"""
用户 | 数据层
"""

from models.po import (
    UserPO,
    UserTokenPO,
)
from my_typing import *
from service.base import ServiceBase
from utils.data_utils.special import ObjectIdStr


class UserService(ServiceBase[UserPO]):
    """ 用户 | 数据层 """

    po = UserPO
    collection_name = "user_user"
    single_field_index = [
        "id",
        "username",
        "nickname",
        "phone",
        "email",
    ]

    @classmethod
    def get_one_by_nickname(cls, nickname: str) -> UserPO | None:
        if not nickname:
            return None

        return cls.find_one({"nickname": nickname})

    @classmethod
    def get_one_by_username(cls, username: str) -> UserPO | None:
        if not username:
            return None

        return cls.find_one({"username": username})

    @classmethod
    def get_one_by_email(cls, email: str) -> UserPO | None:
        if not email:
            return None

        return cls.find_one({"email": email})

    @classmethod
    def get_one_by_phone(cls, phone: str) -> UserPO | None:
        if not phone:
            return None

        return cls.find_one({"phone": phone})

    @classmethod
    def get_one_by_union_username(
        cls,
        union_username: str,
        union_fields: ListStr,
    ) -> UserPO | None:
        if not (
            union_username
            and union_fields
        ):
            return None

        query = {
            "$or": [
                {_field: union_username}
                for _field in union_fields
            ]
        }

        return cls.find_one(query)

    @classmethod
    def get_one_by_avatar_id(cls, avatar_id: ObjectIdStr) -> UserPO | None:
        if not avatar_id:
            return None

        query = {"avatar_id": avatar_id}

        return cls.find_one(query)


class UserTokenService(ServiceBase[UserTokenPO]):
    """ 用户 Token 数据层 """

    po = UserTokenPO
    collection_name = "user_user_token"
    single_field_index = [
        "user_id",
    ]

    @classmethod
    def get_one_by_key(cls, key: StrOrNone) -> UserTokenPO | None:
        if not key:
            return None

        return cls.find_one({"key": key})

    @classmethod
    def get_one_by_user_id(cls, user_id: ObjectIdStr | None) -> UserTokenPO | None:
        if not user_id:
            return None

        return cls.find_one({"user_id": user_id})


if __name__ == "__main__":
    from devtools import debug

    from models import PageQuery

    res = UserService.paginated_query(PageQuery())
    debug(res)
    debug(res.model_dump())
    res1: UserPO = UserService.find_one()
    debug(res1)
    debug(res1.is_deleted)
    debug(UserService.get_one_by_username("test"))
